package com.example.hello.controller;

import com.example.hello.common.Result;
import com.example.hello.dto.CommentDTO;
import com.example.hello.entity.Comment;
import com.example.hello.security.UserDetailsServiceImpl;
import com.example.hello.service.CommentService;
import com.github.pagehelper.PageInfo;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/api/comment")
@Tag(name = "留言管理", description = "提供留言的增删改查接口")
public class CommentController {

    @Autowired
    private CommentService commentService;
    
    @Autowired
    private UserDetailsServiceImpl userDetailsService;

    /**
     * 添加留言
     */
    @PostMapping("/addComment")
    @PreAuthorize("isAuthenticated()")
    @Operation(summary = "添加留言", description = "添加新的留言，需要用户登录", 
            security = @SecurityRequirement(name = "JWT"))
    @ApiResponses(value = {
            @ApiResponse(responseCode = "200", description = "添加成功"),
            @ApiResponse(responseCode = "401", description = "未授权"),
            @ApiResponse(responseCode = "500", description = "服务器内部错误")
    })
    public Result<Comment> addComment(@RequestBody CommentDTO commentDTO) {
        try {
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            UserDetails userDetails = (UserDetails) authentication.getPrincipal();
            Long userId = userDetailsService.getUserIdByUsername(userDetails.getUsername());
            
            Comment comment = commentService.addComment(commentDTO, userId);
            return Result.success(comment);
        } catch (Exception e) {
            return Result.error(500, e.getMessage());
        }
    }

    /**
     * 删除留言
     */
    @PostMapping("/deleteComment/{commentId}")
    @PreAuthorize("isAuthenticated()")
    @Operation(summary = "删除留言", description = "用户删除自己的留言，需要用户登录", 
            security = @SecurityRequirement(name = "JWT"))
    @ApiResponses(value = {
            @ApiResponse(responseCode = "200", description = "删除成功"),
            @ApiResponse(responseCode = "401", description = "未授权"),
            @ApiResponse(responseCode = "500", description = "服务器内部错误")
    })
    public Result<Boolean> deleteComment(
            @Parameter(description = "留言ID", required = true) 
            @PathVariable Long commentId) {
        try {
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            UserDetails userDetails = (UserDetails) authentication.getPrincipal();
            Long userId = userDetailsService.getUserIdByUsername(userDetails.getUsername());
            
            return Result.success(commentService.deleteComment(commentId, userId));
        } catch (Exception e) {
            return Result.error(500, e.getMessage());
        }
    }

    /**
     * 获取留言列表
     */
    @GetMapping("/attraction/{attractionId}")
    @Operation(summary = "获取留言列表", description = "获取指定景点的留言列表")
    @ApiResponses(value = {
            @ApiResponse(responseCode = "200", description = "获取成功")
    })
    public Result<PageInfo<Comment>> getCommentList(
            @Parameter(description = "景点ID", required = true) 
            @PathVariable Long attractionId,
            @Parameter(description = "页码", required = false) 
            @RequestParam(defaultValue = "1") Integer pageNum,
            @Parameter(description = "每页数量", required = false) 
            @RequestParam(defaultValue = "10") Integer pageSize) {
        try {
            return Result.success(commentService.getCommentsByAttractionId(attractionId, pageNum, pageSize));
        } catch (Exception e) {
            return Result.error(500, "服务器内部错误: " + e.getMessage());
        }
    }

    /**
     * 管理员删除留言
     */
    @PostMapping("/admin/deleteComment/{commentId}")
    @PreAuthorize("hasRole('ROLE_ADMIN')")
    @Operation(summary = "管理员删除留言", description = "管理员删除任意留言，需要管理员权限", 
            security = @SecurityRequirement(name = "JWT"))
    @ApiResponses(value = {
            @ApiResponse(responseCode = "200", description = "删除成功"),
            @ApiResponse(responseCode = "401", description = "未授权"),
            @ApiResponse(responseCode = "403", description = "权限不足"),
            @ApiResponse(responseCode = "500", description = "服务器内部错误")
    })
    public Result<Boolean> adminDeleteComment(
            @Parameter(description = "留言ID", required = true) 
            @PathVariable Long commentId) {
        try {
            return Result.success(commentService.adminDeleteComment(commentId));
        } catch (Exception e) {
            return Result.error(500, e.getMessage());
        }
    }

    /**
     * 获取留言详情
     */
    @GetMapping("/{commentId}")
    @Operation(summary = "获取留言详情", description = "根据ID获取留言详细信息")
    @ApiResponses(value = {
            @ApiResponse(responseCode = "200", description = "获取成功")
    })
    public Result<Comment> getCommentById(
            @Parameter(description = "留言ID", required = true) 
            @PathVariable Long commentId) {
        try {
            return Result.success(commentService.getCommentById(commentId));
        } catch (Exception e) {
            return Result.error(500, e.getMessage());
        }
    }

    /**
     * 获取个人留言列表
     */
    @GetMapping("/user")
    @PreAuthorize("isAuthenticated()")
    @Operation(summary = "获取个人留言列表", description = "获取当前登录用户的留言列表", 
            security = @SecurityRequirement(name = "JWT"))
    @ApiResponses(value = {
            @ApiResponse(responseCode = "200", description = "获取成功"),
            @ApiResponse(responseCode = "401", description = "未授权")
    })
    public Result<PageInfo<Comment>> getUserComments(
            @Parameter(description = "页码，默认1") 
            @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
            @Parameter(description = "每页大小，默认10") 
            @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize) {
        try {
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            UserDetails userDetails = (UserDetails) authentication.getPrincipal();
            Long userId = userDetailsService.getUserIdByUsername(userDetails.getUsername());
            
            return Result.success(commentService.getCommentsByUserId(userId, pageNum, pageSize));
        } catch (Exception e) {
            return Result.error(500, e.getMessage());
        }
    }

    /**
     * 管理员修改留言状态
     */
    @PostMapping("/admin/updateStatus/{commentId}/{status}")
    @PreAuthorize("hasRole('ROLE_ADMIN')")
    @Operation(summary = "修改留言状态", description = "管理员修改留言状态，需要管理员权限", 
            security = @SecurityRequirement(name = "JWT"))
    @ApiResponses(value = {
            @ApiResponse(responseCode = "200", description = "修改成功"),
            @ApiResponse(responseCode = "401", description = "未授权"),
            @ApiResponse(responseCode = "403", description = "权限不足"),
            @ApiResponse(responseCode = "500", description = "服务器内部错误")
    })
    public Result<Boolean> updateCommentStatus(
            @Parameter(description = "留言ID", required = true) 
            @PathVariable Long commentId,
            @Parameter(description = "状态", required = true) 
            @PathVariable Integer status) {
        try {
            return Result.success(commentService.updateCommentStatus(commentId, status));
        } catch (Exception e) {
            return Result.error(500, e.getMessage());
        }
    }

    /**
     * 管理员设置留言置顶
     */
    @PostMapping("/admin/setTop/{commentId}/{isTop}")
    @PreAuthorize("hasRole('ROLE_ADMIN')")
    @Operation(summary = "设置留言置顶", description = "管理员设置留言置顶状态，需要管理员权限", 
            security = @SecurityRequirement(name = "JWT"))
    @ApiResponses(value = {
            @ApiResponse(responseCode = "200", description = "设置成功"),
            @ApiResponse(responseCode = "401", description = "未授权"),
            @ApiResponse(responseCode = "403", description = "权限不足"),
            @ApiResponse(responseCode = "500", description = "服务器内部错误")
    })
    public Result<Boolean> setCommentTop(
            @Parameter(description = "留言ID", required = true) 
            @PathVariable Long commentId,
            @Parameter(description = "是否置顶", required = true) 
            @PathVariable Boolean isTop) {
        try {
            return Result.success(commentService.setCommentTop(commentId, isTop));
        } catch (Exception e) {
            return Result.error(500, e.getMessage());
        }
    }

    /**
     * 获取置顶留言
     */
    @GetMapping("/top/{attractionId}")
    @Operation(summary = "获取置顶留言", description = "获取指定景点的置顶留言")
    @ApiResponses(value = {
            @ApiResponse(responseCode = "200", description = "获取成功")
    })
    public Result<List<Comment>> getTopComments(
            @Parameter(description = "景点ID", required = true) 
            @PathVariable Long attractionId) {
        try {
            return Result.success(commentService.getTopComments(attractionId));
        } catch (Exception e) {
            return Result.error(500, e.getMessage());
        }
    }

    /**
     * 点赞留言
     */
    @PostMapping("/like/{commentId}")
    @PreAuthorize("isAuthenticated()")
    @Operation(summary = "点赞留言", description = "对留言进行点赞，需要用户登录", 
            security = @SecurityRequirement(name = "JWT"))
    @ApiResponses(value = {
            @ApiResponse(responseCode = "200", description = "点赞成功"),
            @ApiResponse(responseCode = "401", description = "未授权"),
            @ApiResponse(responseCode = "500", description = "服务器内部错误")
    })
    public Result<Boolean> likeComment(
            @Parameter(description = "留言ID", required = true) 
            @PathVariable Long commentId) {
        try {
            return Result.success(commentService.likeComment(commentId));
        } catch (Exception e) {
            return Result.error(500, e.getMessage());
        }
    }

    /**
     * 获取所有留言列表
     */
    @GetMapping("/list")
    @Operation(summary = "获取所有留言列表", description = "获取所有留言列表，允许公开访问，支持排序和状态筛选")
    @ApiResponses(value = {
            @ApiResponse(responseCode = "200", description = "获取成功")
    })
    public Result<PageInfo<Comment>> getAllComments(
            @Parameter(description = "页码", required = false) 
            @RequestParam(defaultValue = "1") Integer pageNum,
            @Parameter(description = "每页数量", required = false) 
            @RequestParam(defaultValue = "10") Integer pageSize,
            @Parameter(description = "排序字段，如：createdAt(默认)、likeCount、rating", required = false)
            @RequestParam(defaultValue = "createdAt") String orderBy,
            @Parameter(description = "排序方式，asc(升序)、desc(降序)", required = false)
            @RequestParam(defaultValue = "desc") String orderDirection,
            @Parameter(description = "状态：0-待审核，1-正常，2-屏蔽", required = false)
            @RequestParam(required = false) Integer status) {
        try {
            return Result.success(commentService.getAllComments(pageNum, pageSize, orderBy, orderDirection, status));
        } catch (Exception e) {
            return Result.error(500, "服务器内部错误: " + e.getMessage());
        }
    }
} 